import requests
import csv
import time
from lxml import etree
import pandas

datas = []

def f_info(url , headers):
    global datas
    r = requests.get(url , headers=headers)
    tree = etree.HTML(r.text)

    if r.status_code == 200:
        songs = tree.xpath('//*[@id="rankWrap"]/div[2]/ul/li')
        for s in songs:
            title = s.xpath('./@title')
            t = title[0].split(' - ')[1]
            z = title[0].split(' - ')[0]

            data = {
                'title': t, '作者': z
            }
            datas.append(data)
if __name__ == '__main__':
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0'
    }

    for i in range(1, 24):
        url = 'https://www.kugou.com/yy/rank/home/{}-8888.html?from=rank'.format(i)
        time.sleep(1)
        print("over",i)

        f_info(url, headers)
    datas = pandas.DataFrame(datas)
    datas.to_csv("./datas.csv")
    print(datas)